#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>

class RateLimiter {
public:
    RateLimiter(int max_concurrent) : max_concurrent_(max_concurrent), current_concurrent_(0) {}

    void Enter() {
        std::unique_lock<std::mutex> lock(mutex_);
        // 等待，直到当前并发数小于最大并发数
        while (current_concurrent_ >= max_concurrent_) {
            cond_.wait(lock);
        }
        // 增加当前并发数
        ++current_concurrent_;
    }

    void Leave() {
        std::unique_lock<std::mutex> lock(mutex_);
        // 减少当前并发数
        --current_concurrent_;
        // 通知其他等待的线程
        cond_.notify_one();
    }

private:
    int max_concurrent_;
    int current_concurrent_;
    std::mutex mutex_;
    std::condition_variable cond_;
};

void Worker(RateLimiter& limiter, int id) {
    limiter.Enter();
    std::cout << "Thread " << id << " is working." << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟工作
    std::cout << "Thread " << id << " finished work." << std::endl;
    limiter.Leave();
}

int main() {
    RateLimiter limiter(3); // 设置最大并发数为3
    std::vector<std::thread> threads;

    for (int i = 0; i < 10; ++i) {
        threads.emplace_back(Worker, std::ref(limiter), i);
    }

    for (auto& thread : threads) {
        thread.join();
    }

    return 0;
}
